package com.beiding.natgo.client;

import com.beiding.natgo.common.Message;
import lombok.extern.slf4j.Slf4j;

import javax.websocket.Session;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
public class SessionHolder {

    private Session session;

    private ClientWorker clientWorker;

    private ClientConfig clientConfig;

    public SessionHolder(Session session) {
        this.session = session;
    }

    private ExecutorService executorService = Executors.newFixedThreadPool(1);

    public void send(Message message) {
        executorService.submit(() -> {
            try {
                ObjectOutputStream outputStream = new ObjectOutputStream(session.getBasicRemote().getSendStream());
                outputStream.writeObject(message);
                outputStream.close();
                //log.info("消息已送达 type={}  msg={}", message.getType(), message.getMsg());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }

    public void sendInitPort() {
        Message message = new Message();
        message.setPort(clientConfig.getServerPort());
        message.setType(2);
        send(message);
    }

    public void createChanel(String chanelId) {

        //创建通道
        this.clientWorker.createChanel(chanelId, this.clientConfig.getHost(), this.clientConfig.getPort());

    }


    public void closeChanel(String chanelId) {
        this.clientWorker.closeChanel(chanelId);
    }

    public void sendData(String chanelId, byte[] data) {
        Message message = new Message();
        message.setType(1);
        message.setChanelId(chanelId);
        message.byteData(data);
        send(message);
    }


    public void sendCreateFail(String id) {
        Message message = new Message();
        message.setType(5);
        message.setChanelId(id);
        send(message);
    }

    public void sendCreateSucess(String id) {
        Message message = new Message();
        message.setType(8);
        message.setChanelId(id);
        send(message);
    }

    public void sendCloseChanel(String id) {
        Message message = new Message();
        message.setChanelId(id);
        message.setType(7);
        send(message);
    }

    public void writeData(String chanelId, byte[] data) {
        clientWorker.writeData(chanelId, data);
    }

    public void setClientConfig(ClientConfig clientConfig) {
        this.clientConfig = clientConfig;
    }

    public ClientWorker getClientWorker() {
        return clientWorker;
    }

    public void startClientWorker() {
        this.clientWorker = new ClientWorker(this);
        this.clientWorker.start();
    }

    public void sendHeart() {
        Message message = new Message();
        message.setType(10);
        send(message);
    }
}
